import os
import subprocess
import sys
import shutil

# 配置文件路径
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 默认配置路径（Windows环境）
DEVECO_DIR = r"/home/txia/xiatian/ohsdk/command-line-tools"
node_path = r"/home/txia/.nvm/versions/node/v18.20.1/bin/node"
npm_path = r"/home/txia/.nvm/versions/node/v18.20.1/bin/npm"
EXCEL_FILE_PATH = os.path.join(PROJECT_DIR, "data", "三方库测试表.xlsx")

# 配置路径
GIT_PATH = r"usr/bin/git"

os.environ["PYTHONUNBUFFERED"] = "1"  # 防止终端输出乱码
os.environ['PYTHONIOENCODING'] = 'utf-8'
os.environ['DEVECO_SDK_HOME'] = r'/home/txia/xiatian/ohsdk/command-line-tools/sdk'
os.environ['OHOS_BASE_SDK_HOME'] = r'/home/txia/xiatian/ohsdk/openharmony'
hvigor_path = os.path.join(DEVECO_DIR, r"hvigor/bin/hvigorw.js")
ohpm_path = os.path.join(DEVECO_DIR, r"ohpm/bin/ohpm")

def check_dependencies():
    """检查必要的依赖项是否安装"""
    required = ['git']
    
    for dep in required:
        # 先检查命令是否存在
        if shutil.which(dep) is None:
            print(f"错误: 找不到{dep}, 请确认已安装并添加到PATH环境变量!")
            sys.exit(1)
        
        # 尝试不同的版本参数
        version_args = ['--version', '-version', '-v']
        
        for arg in version_args:
            try:
                result = subprocess.run([dep, arg], check=True,
                                      stdout=subprocess.PIPE, 
                                      stderr=subprocess.PIPE,
                                      text=True,
                                      timeout=10)
                # 如果成功执行，跳出内部循环
                print(f"{dep} 已安装: {result.stdout.strip()}")
                break
            except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
                # 如果是最后一个参数尝试仍然失败，则报错
                if arg == version_args[-1]:
                    print(f"错误: {dep} 版本检查失败!")
                    sys.exit(1)
                # 否则继续尝试下一个参数
                continue

# SDK版本与API版本的映射关系
SDK_API_MAPPING = {
    "5.0.0": "12",
    "5.0.1": "13",
    "5.0.2": "14",
    "5.0.3": "15",
    "5.0.4": "16",
    "5.0.5": "17",
    "5.1.0": "18",
    "5.1.1": "19",
    "6.0.0": "20"
}

# 全局变量存储用户选择的SDK版本
selected_sdk_version = None
selected_api_version = None

def set_sdk_version(sdk_version):
    """设置SDK版本和对应的API版本"""
    global selected_sdk_version, selected_api_version
    selected_sdk_version = sdk_version
    selected_api_version = get_api_version(sdk_version)

def get_api_version(sdk_version):
    """根据SDK版本获取对应的API版本号"""
    if sdk_version in SDK_API_MAPPING:
        return SDK_API_MAPPING[sdk_version]
    # 如果找不到对应版本，返回最新版本
    print(f"警告：未找到SDK版本 {sdk_version} 对应的API版本，将使用最新版本")
    return list(SDK_API_MAPPING.values())[-1]
